<template>
  <h1 v-if="route.path==='/home/addemps'">添加员工</h1>
  <h1 v-else>修改员工</h1>
  <el-form
    :model="form.data"
    :rules="rules"
    ref="ruleFormRef"
    :hide-required-asterisk="true"
    label-width="120px">

    <el-form-item label="员工姓名" prop="employeeName">
      <el-input v-model="form.data.employeeName" placeholder="请输入员工的姓名" style="width: 218px;" />
    </el-form-item>

    <el-form-item label="员工账号" prop="userAccount">
      <el-input v-model="form.data.userAccount" placeholder="请输入员工账号" style="width: 218px;" />
    </el-form-item>

    <el-form-item label="员工手机号" prop="phone">
      <el-input v-model="form.data.phone" placeholder="请输入员工手机号" style="width: 218px;" />
    </el-form-item>

    <el-row>

      <el-col :span="6">
        <el-form-item label="部门" prop="departmentId">
          <el-select v-model="form.data.departmentId" placeholder="请选择所属部门">
            <el-option v-for="item in departments.data"
                       :key="item.departmentId"
                       :label="item.departmentName"
                       :value="item.departmentId" />
          </el-select>
        </el-form-item>
      </el-col>


<!--      <el-col :span="6">-->
<!--        <el-form-item label="职务" prop="position">-->
<!--          <el-select v-model="form.data.position" placeholder="请选择职务">-->
<!--            <el-option v-for="item in positions.data"-->
<!--                       :key="item.position"-->
<!--                       :label="item.position"-->
<!--                       :value="item.position" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--      </el-col>-->

      <el-col :span="6">
        <el-form-item label="薪资" prop="salaryType">
          <el-select v-model="form.data.salaryType" placeholder="薪资">
            <el-option v-for="item in salary.data"
                       :key="item.slarayId"
                       :label="(item.total/100).toFixed(2)+'元'"
                       :value="item.slarayId" />
          </el-select>
        </el-form-item>
      </el-col>

    </el-row>


    <el-form-item label="生日" style="width:330px" prop="bithday">
      <el-date-picker
        v-model="form.data.bithday"
        type="date"
        placeholder="请选择日期"
        style="width:300px;"
        format="YYYY/MM/DD"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

<!--    <el-form-item label="角色" style="width: 330px" prop="roler">-->
<!--      <el-select v-model="form.data.roler" placeholder="请输入员工的角色">-->
<!--        <el-option label="管理员" value="admin" />-->
<!--        <el-option label="普通员工" value="user" />-->
<!--      </el-select>-->
<!--    </el-form-item>-->

    <el-form-item label="性别" prop="gender">
      <el-radio-group v-model="form.data.gender">
        <el-radio label="男" />
        <el-radio label="女" />
      </el-radio-group>
    </el-form-item>


    <el-form-item>
      <el-button  type="primary" @click="onSubmit(ruleFormRef)" v-if="route.path==='/home/addemps'">添加</el-button>
      <el-button v-else type="primary" @click="onSubmit(ruleFormRef)">修改</el-button>
      <el-button @click="reset">重置</el-button>
    </el-form-item>
  </el-form>

</template>

<script lang="js" setup>
import { onMounted, reactive, ref, toRaw, toRefs, unref } from "vue";
import {
  addEmployee,
  deleteEmployeeById,
  getDepartmentNameId,
  getEmployeeOne,
  login,
  updateEmployee
} from "@/utils/api";
import { getSalaryTotalAndType } from "@/utils/salaryRequest";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import router from "@/router";

const route = useRoute();

const form = reactive({
  data: {
    "bithday": "",
    "departmentId": "",
    "gender": "",
    "name": "",
    "phone": "",
    "position": "正式员工",
    "roler": "user",
    "salaryType": "",
    "userAccount": ""
  }
});


//表单校验规则
const rules = reactive({
  employeeName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    {min:2,max:10,message: "姓名长度为2~10", trigger: "blur"}
  ],
  userAccount: [
    { required: true, message: "请输入员工账号", trigger: "blur" },
    {min:8,max:10,message: "姓名长度为8~10", trigger: "blur"}
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
  ],
  departmentId: [
    { required: true, message: "请选择部门", trigger: "blur" }
  ],
  position: [
    { required: true, message: "请选择职务", trigger: "blur" }
  ],
  salaryType: [
    { required: true, message: "请选择薪资", trigger: "blur" }
  ],
  bithday: [
    { required: true, message: "请输入日期", trigger: "blur" }
  ],
  roler: [
    { required: true, message: "员工的角色", trigger: "blur" }
  ],
  gender: [
    { required: true, message: "必须选择性别", trigger: "blur" }
  ]
});

const departments = reactive({
  data: []
});

const positions = reactive({
  data: [
    {
      position: "实习生"
    },
    {
      position: "正式员工"
    }
  ]
});

const salary = reactive({
  data: []
});


const ruleFormRef = ref();

//获取部门菜单的数据
const getDepartmentOptionData = async () => {
  let res = await getDepartmentNameId();
  departments.data = res.data;
};

//获取薪资菜单的数据
const getSalaryOptionData = async () => {
  let res = await getSalaryTotalAndType();
  salary.data = res.data;
};




//重置
const reset = () => {
  form.data = {}
}

onMounted(() => {
  getDepartmentOptionData();
  getSalaryOptionData();
  if (route.path !== '/home/addemps'){
    UpdateEmplyeeDate()
  }
});


//发送添加请求
const addEmployeeRequest = async (fromDate) => {
  let res = await addEmployee(fromDate);
  if (res.data) {
    ElMessage({
      type: "success",
      message: "添加成功成功"
    });
    router.push({
      path:'/home/emps'
    })
  }
};

//回显要修改员工的数据
const UpdateEmplyeeDate = async () =>{
  let res = await getEmployeeOne(route.query.id)
  form.data = res.data
  let dep = departments.data.filter(i=>i.departmentName === res.data.departmentName)
  form.data.departmentId = toRaw(dep)[0].departmentId
  let sal = salary.data.filter(i=>i.total === res.data.salary)
  form.data.salaryType = toRaw(sal)[0].slarayId
}



//提交表单的回调
const onSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (!valid) {
      return false;
    } else {
      //发送请求
      if (route.path==='/home/addemps'){
        addEmployeeRequest(form.data);
      }else {
        ElMessageBox.confirm(
          "确定要修改吗?",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(async () => {
            //发送修改的请求
            let res = await updateEmployee(form.data);
            if (res.data) {
              ElMessage({
                type: "success",
                message: "修改成功"
              });
              router.push({
                path:'/home/emps'
              })
            } else {
              ElMessage({
                type: "error",
                message: "修改失败"
              });
            }
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "取消修改"
            });
          });
      }
    }
  });
};

</script>


<style scoped>
</style>